package git.soulbgm.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Iterator;
import java.util.List;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2018-10-16 15:11
 * @description
 */
@Component
@Controller("/upload")
public class UploadResource {

    @Autowired
    HttpServletRequest request;

    @RequestMapping(value = "/uploadTest", method = RequestMethod.POST)
//    @Consumes(MediaType.MULTIPART_FORM_DATA)
//    @Produces(MediaType.APPLICATION_JSON)
    public String upload() throws Exception {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    // 接收表单里的参数
                    if (item.getFieldName().equals("file.path")) {
                        String json = item.getString("UTF-8");
                        System.out.println("接收参数json：" + json);
                    }
                } else {
                    // 存储文件
                    FileUtils.copyInputStreamToFile(item.getInputStream(), new File(request.getRealPath("/") + "upload/" + item.getFieldName()));


                }
            }

        }
        return "上传成功了";
    }

}
